/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlets.movil;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import negocio.GestorAppMovilLocal;
import negocio.GestorLogueoLocal;

/**
 *
 * @author Ing. Monica Merlo, Ing. Agustin  Fernandez
 */
public class WapServlet extends HttpServlet {

    @EJB(beanName = "GestorLogueoBean")
    private GestorLogueoLocal gestorLogueoBean;
    @EJB(beanName = "GestorAppMovilBean")
    private GestorAppMovilLocal gestorAppMovilBean;

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String usuario = request.getParameter("usuarioSigeo");
            String clave = request.getParameter("claveSigeo");
            String eliminarDirUsuario = request.getParameter("eliminarJarJadUsuario");
            if ((usuario == null && clave == null) || (usuario.equals("") && clave.equals(""))) {
                response.setContentType("text/vnd.wap.wml");
                out.println("<?xml version=\"1.0\"?>");
                out.println("<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.3//EN\" \"http://www.wapforum.org/DTD/wml13.dtd\">");
                out.println("<wml>");
                out.println("<card id=\"card1\" title=\"SiGeo\">");
                out.println("<p>");
                out.println("<b>Por favor ingrese su usuario y password para descargar la aplicacion</b><br/><br/>");
                out.println("<table columns=\"2\">");
                out.println("<tr>");
                out.println("<td>");
                out.println("<b>Usuario:</b>");
                out.println("</td>");
                out.println("<td>");
                out.println("<input type=\"text\" name=\"name\" maxlength=\"250\" value=\"\"/><br/>");
                out.println("</td>");
                out.println("</tr>");
                out.println("<tr>");
                out.println("<td>");
                out.println("<b>Password:</b>");
                out.println("</td>");
                out.println("<td>");
                out.println("<input type=\"password\" name=\"passwd\" maxlength=\"250\" value=\"\"/><br/>");
                out.println("</td>");
                out.println("</tr>");
                out.println("</table>");
                out.println("<br/>");
                out.println("<anchor>");
                out.println("<go method=\"post\" href=\"" + request.getContextPath() + "/wap\">");
                out.println("<postfield name=\"usuarioSigeo\" value=\"$(name)\"/>");
                out.println("<postfield name=\"claveSigeo\" value=\"$(passwd)\"/>");
                out.println("</go>");
                out.println("Aceptar");
                out.println("</anchor>");
                out.println("</p>");
                out.println("</card>");
                out.println("</wml>");
                if (eliminarDirUsuario != null) {
                    if (!eliminarDirUsuario.equals("")) {
                        File fDestino = new File(this.getServletContext().getRealPath("/descarga/SiGeoJ2ME.jar"));
                        File fileDestinoUsuario = new File(fDestino.getParent() + File.separator + eliminarDirUsuario, "SiGeoJ2ME.jar");
                        File dirUsuario = new File(fileDestinoUsuario.getParent());
                        gestorAppMovilBean.eliminarDirectorioUsuario(dirUsuario);
                    }
                }
            } else {
                if (!usuario.equals("") && !clave.equals("")) {
                    datos.Usuario usu = gestorLogueoBean.validarUsuario(usuario, clave);
                    if (usu != null) {
                        URL url = this.getClass().getResource("/configuracion/SiGeoJ2ME.jar");
                        File fJar = new File(url.getFile());
                        url = getClass().getResource("/configuracion/SiGeoJ2ME.jad");
                        File fJad = new File(url.getFile());
                        url = getClass().getResource("/configuracion/MANIFEST.MF");
                        File fMani = new File(url.getFile());
                        File fDestino = new File(this.getServletContext().getRealPath("/descarga/SiGeoJ2ME.jar"));
                        String puerto = String.valueOf(request.getServerPort());
                        if (puerto != null) {
                            if (!puerto.equals("0")) {
                                puerto = ":" + request.getServerPort();
                            } else {
                                puerto = "";
                            }
                        } else {
                            puerto = "";
                        }
                        String urlJar = "http://" + request.getServerName() + puerto + request.getContextPath() + "/descarga/" + usuario + "/";

                        gestorAppMovilBean.generarJarParaDescarga(fJar, fJad, fMani, fDestino, urlJar, usuario, clave);
                        response.setContentType("text/vnd.wap.wml");
                        out.println("<?xml version=\"1.0\"?>");
                        out.println("<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.3//EN\" \"http://www.wapforum.org/DTD/wml13.dtd\">");
                        out.println("<wml>");
                        out.println("<card id=\"card2\" title=\"SiGeo\">");
                        out.println("<p>");
                        out.println("<b>Sus archivos:</b><br/><br/>");
                        out.println("<a href=\"" + urlJar + "SiGeoJ2ME.jar\">SiGeoJ2ME.jar</a><br/>");
                        out.println("<a href=\"" + request.getContextPath() + "/descarga/" + usuario + "/SiGeoJ2ME.jad\">SiGeoJ2ME.jad</a><br/>");
                        out.println("<br/>");
                        out.println("<anchor>");
                        out.println("<go method=\"post\" href=\"" + request.getContextPath() + "/wap\">");
                        out.println("<postfield name=\"usuarioSigeo\" value=\"\"/>");
                        out.println("<postfield name=\"claveSigeo\" value=\"\"/>");
                        out.println("<postfield name=\"eliminarJarJadUsuario\" value=\"" + usuario + "\"/>");
                        out.println("</go>");
                        out.println("Aceptar");
                        out.println("</anchor>");
                        out.println("</p>");
                        out.println("</card>");
                        out.println("</wml>");
                    } else {
                        response.setContentType("text/vnd.wap.wml");
                        out.println("<?xml version=\"1.0\"?>");
                        out.println("<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.3//EN\" \"http://www.wapforum.org/DTD/wml13.dtd\">");
                        out.println("<wml>");
                        out.println("<card id=\"card1\" title=\"SiGeo\">");
                        out.println("<p>");
                        out.println("<b>Usuario o password incorrectos!!!</b><br/><br/>");
                        out.println("<anchor>");
                        out.println("<go method=\"post\" href=\"" + request.getContextPath() + "/wap\">");
                        out.println("<postfield name=\"usuarioSigeo\" value=\"\"/>");
                        out.println("<postfield name=\"claveSigeo\" value=\"\"/>");
                        out.println("</go>");
                        out.println("Aceptar");
                        out.println("</anchor>");
                        out.println("</p>");
                        out.println("</card>");
                        out.println("</wml>");
                    }
                } else {
                    response.setContentType("text/vnd.wap.wml");
                    out.println("<?xml version=\"1.0\"?>");
                    out.println("<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.3//EN\" \"http://www.wapforum.org/DTD/wml13.dtd\">");
                    out.println("<wml>");
                    out.println("<card id=\"card1\" title=\"SiGeo\">");
                    out.println("<p>");
                    out.println("<b>Tiene que ingresar su usuario y password para poder descargar la aplicacion</b><br/><br/>");
                    out.println("<anchor>");
                    out.println("<go method=\"post\" href=\"" + request.getContextPath() + "/wap\">");
                    out.println("<postfield name=\"usuarioSigeo\" value=\"\"/>");
                    out.println("<postfield name=\"claveSigeo\" value=\"\"/>");
                    out.println("</go>");
                    out.println("Aceptar");
                    out.println("</anchor>");
                    out.println("</p>");
                    out.println("</card>");
                    out.println("</wml>");
                }
            }
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
